package com.ict.web.rabbitMqConfig;


import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ict.common.core.domain.entity.SysDept;
import com.ict.common.core.domain.entity.SysUser;
import com.ict.common.utils.SecurityUtils;
import com.ict.common.utils.StringUtils;
import com.ict.system.mapper.SysUserMapper;
import com.ict.system.mapper.SysUserRoleMapper;
import com.ict.system.service.ISysDeptService;
import com.ict.system.service.ISysUserService;
import com.ict.web.constant.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


/**
 * @author xc
 */
@Slf4j
//@Configuration 测试环境不接入mq
public class RabbitListenerConfig  {
    //appCode需自行在能力管控平台（http://23.99.215.138:9300/login）申请

    private static final String APP_CODE="smartcity_user_sync";
//    private static final String USER_URL="http://23.99.215.138:21100/rest";//用户接口政务外网地址
    private static final String USER_URL="http://100.100.104.12:21100/rest";//用户接口代理地址
    private static final String USER_API_CODE="API_CODE_16299613280186989000";
//    private static final String DEPT_URL="http://23.99.215.138:21100/rest";//部门接口政务外网地址
    private static final String DEPT_URL="http://100.100.104.12:21100/rest";//部门接口代理地址
    private static final String DEPT_API_CODE="API_CODE_1630029712265597200";
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private SysUserRoleMapper userRoleMapper;
    @Autowired
    private SysUserMapper userMapper;
    @RabbitListener(bindings = @QueueBinding(
//            value = @Queue(value = "ums.projectApproval", durable = "true"),//测试环境队列
            value = @Queue(value = "ums.approval", durable = "true"),//生产环境队列
            exchange = @Exchange(value = "ums.notice.exchange", ignoreDeclarationExceptions = "true", type = ExchangeTypes.FANOUT)
    ))

    public void handleMessage(String msg){
        log.info("--------------------------------------------------------------------"+msg);
        // todo 对监听到的数据进行下一步处理
        try {
            //处理RabbitMq监听数据并封装监听对象
            ListenerDomain listenerDomain = JSON.parseObject(msg,ListenerDomain.class);
//            List<String> usernameList = Arrays.asList(listenerDomain.getUsernames().split(","));
            //TODO:校验本地数据库是否存在该用户：
            //                                不存在：调用第三方接口同步数据
            //                                存在：校验监听信息中的用户是否更新：更新则同步数据到本地数据库
            SysUser sysUser = userService.selectUserByUserName(listenerDomain.getUsernames());
            //调用第三方接口-用户信息接口获取用户数据
            String userInformation = callUserInterface(listenerDomain.getUsernames());
            JSONObject object = JSONObject.parseObject(userInformation);
            JSONObject object1 = JSONObject.parseObject(object.getString("result"));
            JSONObject object2 = JSONObject.parseObject(object1.get("result").toString());
            String records = object2.get("records").toString();
            List<UserDomain> userDomain = JSONArray.parseArray(records, UserDomain.class);
            log.info("userDomain-------"+userDomain);
            if(ListenerDomain.OPERATION_ADD.equals(listenerDomain.getOperation())){
                if(StringUtils.isEmpty(userInformation)){
                    SysUser user = new SysUser();
                    findUser(userDomain.get(0), user);
                    user.setStatus(Constants.DELETE_STATUS_NORMAL);
                    userService.insertUser(user);
                }
            }else if(ListenerDomain.OPERATION_EDIT.equals(listenerDomain.getOperation())){
                SysUser user = findUser(userDomain.get(0),sysUser);
                user.setStatus(Constants.DELETE_STATUS_NORMAL);
                userService.updateUser(user);
            }else if(ListenerDomain.OPERATION_DELETE.equals(listenerDomain.getOperation())){
                // 删除用户与角色关联
                userRoleMapper.deleteUserRoleByUserId(sysUser.getUserId());
                // 删除用户
                userMapper.deleteById(sysUser.getUserId());
            }
        }catch (Exception e){
            e.printStackTrace();
            log.info(e.getMessage());
        }
    }

    /**
     * 封装本地用户对象
     * @param userDomain
     * @param user
     * @return
     */
    public SysUser findUser(UserDomain userDomain,SysUser user){
        //查询用户部门
        if(StringUtils.isNotEmpty(userDomain.getDepartIds_dictText())){
            List<String> deptList = Arrays.asList(userDomain.getDepartIds().split(","));
            SysDept sysDept = deptService.selectDept(deptList.get(0));
            if(StringUtils.isNotNull(sysDept)){
                user.setDeptId(sysDept.getDeptId());
            }
        }
        user.setUserName(userDomain.getUsername());
        user.setNickName(userDomain.getRealname()!=null?userDomain.getRealname():null);
        user.setPhonenumber(userDomain.getPhone()!=null?userDomain.getPhone():null);
        user.setSex(userDomain.getSex()=="1"?"0":"1");
        user.setStatus(userDomain.getStatus()=="1"?"0":"1");
        user.setDelFlag(userDomain.getDelFlag()!=null?userDomain.getDelFlag():null);
        user.setCreateTime(new Date());
        user.setCreateBy("admin");
        user.setPassword(SecurityUtils.encryptPassword("test123"));
        return user;
    }
    /**
     * 调用用户信息接口
     * @param usernames
     * @return
     */
    public String callUserInterface(String usernames){
        JSONObject jsonUser = new JSONObject();
        jsonUser.put("username", usernames);
        HashMap<String, String> headersUser = new HashMap<>();
        headersUser.put("appCode", APP_CODE);
        headersUser.put("apiCode", USER_API_CODE);
        headersUser.put("apiVersion", "1.0.0");
        headersUser.put("format", "restful");
        headersUser.put("Content-Type", "application/json");
        return HttpUtil.createGet(USER_URL).addHeaders(headersUser).form(jsonUser).execute().body();
    }
    /**
     * 调用部门信息接口
     * @param deptIds
     * @return
     */
    public String callDeptInterface(String deptIds){
        JSONObject jsonDept = new JSONObject();
        jsonDept.put("departIds", deptIds);
        HashMap<String, String> headersDept = new HashMap<>();
        headersDept.put("appCode", APP_CODE);
        headersDept.put("apiCode", DEPT_API_CODE);
        headersDept.put("apiVersion", "1.0.0");
        headersDept.put("format", "restful");
        headersDept.put("Content-Type", "application/json");
        return  HttpUtil.createGet(DEPT_URL).addHeaders(headersDept).form(jsonDept).execute().body();
    }
}
